﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.Design;
using System.Configuration;
using System.Xml;

namespace MetadataBasedConfigArch.ExpressionWeb.ExpressionBuilders
{
    public class XmlExpressionEditor : System.Web.UI.Design.ExpressionEditor
    {
        public override object EvaluateExpression(string expression, object parseTimeData, Type propertyType, IServiceProvider serviceProvider)
        {
            if (serviceProvider != null)
            {
                IWebApplication service = serviceProvider.GetService(typeof(IWebApplication)) as IWebApplication;
                if (service != null)
                {
                    Configuration configuration = service.OpenWebConfiguration(true);
                    if (configuration != null)
                    {
                        string configPath = configuration.FilePath.Substring(0, configuration.FilePath.LastIndexOf("\\"));
                        string[] keys = expression.Split(",".ToArray());
                        string xmlFileName = System.IO.Path.Combine(configPath, "data\\" + keys[0]);
                        return GetXmlValue(keys[1], xmlFileName);
                    }
                }
            }
            return null;
        }

        public override ExpressionEditorSheet GetExpressionEditorSheet(string expression, IServiceProvider serviceProvider)
        {
            return base.GetExpressionEditorSheet(expression, serviceProvider);
        }

        public static string GetXmlValue(string key,string fileFullName)
        {
            string[] keys = key.Split(",".ToArray()); 
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(fileFullName);
            XmlNode node = xmlDoc.SelectSingleNode(keys[1]);
            if (node != null)
            {
                return node.InnerText;
            }
            return String.Empty;
        }

    }

    public class XmlExpressionEditorSheet : ExpressionEditorSheet
    {
        public XmlExpressionEditorSheet(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {
        }
        public override string GetExpression()
        {
            throw new NotImplementedException();
        }
                
    }
}